define(["mock", "allTpl", "dropload", "lazyload","cookie"], function (Mock, template, dropload, lazyload, cookie) {
    return {
        init: function () {
            this.scroll();
            this.swiper();
            this.activity();
            this.topMenu();
        },
        //延时加载
        scroll:function(){
            var G =this,
                timer = null,
                threshold = 200, // 距离视窗顶部加载距离
                recommend_isLoad = false,
                classType_isLoad = false,
                $IndexPage = $("#IndexPage"),
                $recommend_IndexPage = $('#recommend_IndexPage'),
                $hotBox_IndexPage = $('#hotBox_IndexPage'),
                $searchBar_IndexPage = $("#searchBar_IndexPage");

            function isVisible( $elem ){
                //如果为true,则 $elem 不在可视区域内.反之则在可视区域内.
                return ( $(window).scrollTop()+$(window).height() ) < ( $elem.offset().top - threshold );
            }

            //滚动显示
            $(window).on("scroll", function(){
                if ($IndexPage.is(":visible")){
                    var top = $(window).scrollTop();
                    if ( timer ){
                        clearTimeout(timer);
                    }
                    opacity(0,0.3);
                    timer = setTimeout(function(){
                        opacity(1,0.3);
                    }, 600)
                }

                //加载推荐商品
                if ( !isVisible($recommend_IndexPage) && !recommend_isLoad ){
                    G.recommend();
                    recommend_isLoad = true;
                }
                //加载热门品类
                if ( !isVisible($hotBox_IndexPage) && !classType_isLoad ){
                    G.classType();
                    classType_isLoad = true;
                }

            });

           var opacity = function(value, sec){
                $searchBar_IndexPage.css({
                    opacity: value,
                    "transition-duration": sec + "s"
                });
            }

        },
        //顶部导航
        topMenu:function(){
            var G = this,

            $IndexPage = $("#IndexPage"),
            $searchBar_IndexPage = $("#searchBar_IndexPage"),
            $searchPage = null,
            html_PersonalCenter = '<a href="" class="icon-my">&#xe91a;</a> ',
            html_close= '<span class="icon-close">&#xe904;</span>',
            SearchData =  $.cookie("SearchData"),
            getArray = SearchData ? JSON.parse($.cookie("SearchData")) : [],
            $input =  $searchBar_IndexPage.find(".md input"),

            //搜索功能
            searchPage = function () {
                $searchPage = $("#searchPage");
                if ($searchPage[0]){
                    $searchPage.show();
                } else {
                    $("body").append(template('Reservation/IndexPage/search_IndexPage'));
                    //显示历史记录
                    if (getArray){
                        $.each(getArray, function(i, item){
                            $("#his_searchPage .bd").prepend('<a href="' + _CONFIG[__webState].listPage_URL + '?keyword=' + encodeURI(item) +'">' +　item +　'</a>');
                        });
                    }
                }
                $IndexPage.hide();
                $searchBar_IndexPage.find(".ld").html(html_close)
                    .on("click",function(){
                        $(this).html(html_PersonalCenter);
                        $input.val("");
                        $IndexPage.show();
                        $searchPage.hide();
                    });
            };



            $input.on({
                "focus": function(){
                    searchPage();
                }
            });


            //搜索
            $searchBar_IndexPage.find(".icon-search").on("click", function(){
                var val_input = $.trim($input.val());
               if ( val_input ){
                   var getString="";
                   if ( SearchData ){
                       getArray.deleteElementByValue(val_input);
                   }
                   getArray.push($input.val());
                   getString = JSON.stringify(getArray);
                   $.cookie("SearchData", getString, { expires: 365, path:"/"});
                   window.location.href = _CONFIG[__webState].listPage_URL + '?keyword=' + encodeURI(val_input);
               } else {
                   popWrap.alert({content:"请输入搜素关键词！", autoClose:800});
               }
                console.log($.cookie("SearchData"));
            });


            //根据值删除数组指定对象
            Array.prototype.deleteElementByValue = function() {
                var what, a = arguments, L = a.length, ax;
                while (L && this.length) {
                    what = a[--L];
                    while ((ax = this.indexOf(what)) !== -1) {
                        this.splice(ax, 1);
                    }
                }
                return this;
            };

        },

        // 大图轮播
        swiper: function (){
            new __base.AjaxFun({
                "url": __base.url.home.GetEPListBy,
                "data":{
                    ebCode: "APP_Ad_00001"
                }
            }, function (data) {
                if (data["Code"] === "0") {
                    $("#showBox_IndexPage .swiper-wrapper").html(template('Reservation/IndexPage/swiper', data['Data']));
                    __base.swiper({target: ".swiper-container"});
                } else {
                    console.log(data['Message']);
                }
            });
        },
        // 热门活动
        activity: function (){
            new __base.AjaxFun({
                "url": __base.url.home.GetEPListBy,
                "data":{
                    ebCode: "APP_Ad_00002"
                }
            }, function (data) {

                if (data["Code"] === "0") {
                    $("#activityBox_IndexPage").html(template('Reservation/IndexPage/activityBox_IndexPage', data['Data']));
                    $(".lazyImg").lazyload({
                        effect : "fadeIn",
                        threshold:150
                    });
                } else {
                    console.log(data['Message']);
                }
            });
        },
        // 热门品类
        classType: function (){
            var __IndexPage = this;
            new __base.AjaxFun({
                "url": __base.url.home.AppPackageList,
                "data":{}
            }, function (data) {

                if (data["Code"] === "0") {
                    var html = template('Reservation/IndexPage/hotBox_IndexPage', data['Data'])
                        .replace(/%URL%/g, _CONFIG[__webState]['subClassPage_URL']);
                        $("#hotBox_IndexPage").html(html);
                        $(".lazyImg").lazyload({
                            effect : "fadeIn",
                            threshold:150
                        });
                } else {
                    console.log(data['Message']);
                }
            });
        },

        // 推荐商品
        recommend: function (){

            var pageIndex = 1,
                isEnd = false,
                $recommend_IndexPage = $('#recommend_IndexPage');



            //$(".listBox",$recommend_IndexPage).html('<div class="dropload-down"><div class="dropload-load"><span class="loading"></span>加载中...</div></div>');


            $recommend_IndexPage.dropload({
                    scrollArea: window,
                    domDown: {      // 下方DOM
                        domClass: 'dropload-down',
                        domRefresh: '<div class="dropload-refresh">↑上拉加载更多</div>',
                        domLoad: '<div class="dropload-load"><span class="loading"></span>加载中...</div>',
                        domNoData: '<div class="dropload-noData">已经是最后一页了</div>'
                    },
                    loadDownFn: function (me) {
                        new __base.AjaxFun({
                            "url": __base.url.home.GetAllRecommend,
                            "data":{
                                pageIndex: pageIndex ++,//页索引
                                pageSize: 8  //页大小
                            }
                        }, function (data) {
                            if (data["Code"] === "0") {
                                if (data["Data"] === null) {
                                    me.isData = false;
                                    me.lock("down");
                                    me.resetload();
                                    return false;
                                }
                                   var html = template('Reservation/IndexPage/recommend_IndexPage', data["Data"])
                                        .replace(/%URL%/g, _CONFIG[__webState].goodsPage_URL);
        
                                    // 为了测试，延迟1秒加载
                                    //setTimeout(function () {
                                        $recommend_IndexPage.find(".listBox").append(html);
                                        // 每次数据加载完，必须重置
                                        me.resetload();
                                    //}, 1000);
                                    // 每次数据加载完，必须重置
                                        $(".lazyImg").lazyload({
                                            effect : "fadeIn",
                                            threshold:150
                                        });

                            } else {
                                console.log(data['Message']);
                            }
                        });
                    }
                });


        }
    };


});
